import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { setLocale, getCurrentLocale } from '@/i18n'

export const useGlobalSettingsStore = defineStore('globalSettings', () => {
  // 语言设置
  const language = ref<'zh-CN' | 'ja-JP' | 'en-US'>(getCurrentLocale() as 'zh-CN' | 'ja-JP' | 'en-US')
  
  // SIMION路径
  const simionPath = ref('')
  
  // 项目路径
  const projectPath = ref('')
  
  // IOB和Lua文件路径
  const iobPath = ref('')
  const luaPath = ref('')
  
  // 扫描类型
  const scanType = ref<'frequency' | 'voltage'>('frequency')
  
  // 频率扫描参数
  const frequencyStart = ref('')
  const frequencyStop = ref('')
  const frequencyStep = ref('')
  
  // 电压扫描参数
  const voltageStart = ref('')
  const voltageStop = ref('')
  const voltageStep = ref('')
  
  // 计算扫描长度
  const frequencyLength = computed(() => {
    const start = parseFloat(frequencyStart.value)
    const stop = parseFloat(frequencyStop.value)
    const step = parseFloat(frequencyStep.value)
    if (isNaN(start) || isNaN(stop) || isNaN(step) || step <= 0) return 0
    return Math.floor((stop - start) / step) + 1
  })
  
  const voltageLength = computed(() => {
    const start = parseFloat(voltageStart.value)
    const stop = parseFloat(voltageStop.value)
    const step = parseFloat(voltageStep.value)
    if (isNaN(start) || isNaN(stop) || isNaN(step) || step <= 0) return 0
    return Math.floor((stop - start) / step) + 1
  })
  
  // 设置SIMION路径
  const setSimionPath = (path: string) => {
    simionPath.value = path
  }
  
  // 设置项目路径
  const setProjectPath = (path: string) => {
    projectPath.value = path
  }
  
  // 设置IOB和Lua文件路径
  const setFilePaths = (iob: string, lua: string) => {
    iobPath.value = iob
    luaPath.value = lua
  }
  
  // 检测项目中的IOB和Lua文件
  const detectProjectFiles = async (projectDir: string) => {
    try {
      if (!(window as any).electronAPI) {
        throw new Error('Electron API不可用')
      }
      
      // 获取项目目录下的所有文件
      const result = await (window as any).electronAPI.listFiles(projectDir)
      if (!result.success) {
        throw new Error(result.error || '获取文件列表失败')
      }
      
      const files = result.files
      
      // 查找IOB文件
      const iobFiles = files.filter((file: any) => 
        file.name.toLowerCase().endsWith('.iob') && !file.isDirectory
      )
      
      // 查找Lua文件
      const luaFiles = files.filter((file: any) => 
        file.name.toLowerCase().endsWith('.lua') && !file.isDirectory
      )
      
      // 匹配IOB和Lua文件
      const matchedPairs: Array<{iob: string, lua: string, baseName: string}> = []
      
      for (const iobFile of iobFiles) {
        const baseName = iobFile.name.replace(/\.iob$/i, '')
        const matchingLua = luaFiles.find((luaFile: any) => 
          luaFile.name.replace(/\.lua$/i, '') === baseName
        )
        
        if (matchingLua) {
          matchedPairs.push({
            iob: iobFile.path,
            lua: matchingLua.path,
            baseName: baseName
          })
        }
      }
      
      return {
        success: true,
        matchedPairs,
        iobFiles: iobFiles.map((f: any) => f.name),
        luaFiles: luaFiles.map((f: any) => f.name)
      }
      
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '未知错误',
        matchedPairs: [],
        iobFiles: [],
        luaFiles: []
      }
    }
  }
  
  // 设置语言
  const setLanguage = (lang: 'zh-CN' | 'ja-JP' | 'en-US') => {
    language.value = lang
    setLocale(lang)
  }
  
  // 设置扫描类型
  const setScanType = (type: 'frequency' | 'voltage') => {
    scanType.value = type
    // 切换类型时清空另一个类型的参数
    if (type === 'frequency') {
      voltageStart.value = ''
      voltageStop.value = ''
      voltageStep.value = ''
    } else {
      frequencyStart.value = ''
      frequencyStop.value = ''
      frequencyStep.value = ''
    }
  }
  
  // 设置频率扫描参数
  const setFrequencyParams = (start: string, stop: string, step: string) => {
    frequencyStart.value = start
    frequencyStop.value = stop
    frequencyStep.value = step
  }
  
  // 设置电压扫描参数
  const setVoltageParams = (start: string, stop: string, step: string) => {
    voltageStart.value = start
    voltageStop.value = stop
    voltageStep.value = step
  }
  
  // 获取当前扫描参数
  const getCurrentScanParams = () => {
    if (scanType.value === 'frequency') {
      return {
        type: 'frequency',
        start: frequencyStart.value,
        stop: frequencyStop.value,
        step: frequencyStep.value,
        length: frequencyLength.value
      }
    } else {
      return {
        type: 'voltage',
        start: voltageStart.value,
        stop: voltageStop.value,
        step: voltageStep.value,
        length: voltageLength.value
      }
    }
  }
  
  // 重置为默认值
  const resetToDefaults = () => {
    language.value = 'zh-CN'
    simionPath.value = ''
    projectPath.value = ''
    iobPath.value = ''
    luaPath.value = ''
    scanType.value = 'frequency'
    frequencyStart.value = ''
    frequencyStop.value = ''
    frequencyStep.value = ''
    voltageStart.value = ''
    voltageStop.value = ''
    voltageStep.value = ''
  }
  
  return {
    // 状态
    language,
    simionPath,
    projectPath,
    iobPath,
    luaPath,
    scanType,
    frequencyStart,
    frequencyStop,
    frequencyStep,
    voltageStart,
    voltageStop,
    voltageStep,
    
    // 计算属性
    frequencyLength,
    voltageLength,
    
    // 方法
    setLanguage,
    setSimionPath,
    setProjectPath,
    setFilePaths,
    detectProjectFiles,
    setScanType,
    setFrequencyParams,
    setVoltageParams,
    getCurrentScanParams,
    resetToDefaults
  }
})
